package com.lanyou.esb.web;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lanyou.cook.common.Constants;
import com.lanyou.esb.entity.IfParameter;
import com.lanyou.esb.repository.IfParameterRepository;
import com.lanyou.esb.web.param.InterfaceParameterParam;

/**
 * 接口参数控制器
 * 
 * @author Davey.wu
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/interfaceParameters")
public class IfParameterController {

	@Autowired
	IfParameterRepository interfaceParameterRepository;

	/**
	 * 获取接口参数
	 * @param param
	 * @param pageable
	 * @return
	 */
	@RequestMapping("/search/findByExample")
	public Page<IfParameter> findByExample(InterfaceParameterParam param,
			Pageable pageable) {

		// 不是选择所有，并且所有条件为空，直接返回
		if (!param.isSelectAll() && StringUtils.isBlank(param.getInterfaceId())
				&& StringUtils.isBlank(param.getInterfaceName())) {
			return new PageImpl<IfParameter>(new ArrayList<>(0), pageable, 0);
		}

		Specification<IfParameter> spec = new Specification<IfParameter>() {
			@Override
			public Predicate toPredicate(Root<IfParameter> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicatesList = new ArrayList<>();

				if (StringUtils.isNotBlank(param.getInterfaceId())) {
					predicatesList.add(cb.like(root.get("http").get("id"),
							'%' + param.getInterfaceId() + '%'));
				}

				if (StringUtils.isNotBlank(param.getInterfaceName())) {
					predicatesList.add(cb.like(root.get("http").get("name"),
							'%' + param.getInterfaceName() + '%'));
				}

				if (StringUtils.isNotBlank(param.getType())) {
					predicatesList.add(cb.like(root.get("type"),
							'%' + param.getType() + '%'));
				}

				query.where(predicatesList.toArray(new Predicate[predicatesList
						.size()]));
				return null;
			}
		};
		Page<IfParameter> result = interfaceParameterRepository.findAll(spec,
				pageable);
		return result;
	}
	
}
